package cn.gs.serializable.serialize;

// @author gs
import cn.gs.serializable.annotation.NSerialize;
import cn.gs.serializable.annotation.NStringClassPair;
import cn.gs.serializable.entity.IEntity;
import cn.gs.reflect.MethodChooser;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

public class AnnotationObjSerialize implements ISerialize {

    private ISerialize serialize(Class<?> clazz) {
        NSerialize ser = clazz.getAnnotation(NSerialize.class);
        if (ser != null) {
            ISerialize i = null;
            try {
                if (null == i && ser.argSerialize().length > 0) {
                    i = MethodChooser.newIntance(ser.value(), ser.argSerialize());
                }
                if (null == i && ser.argString().length > 0) {
                    i = MethodChooser.newIntance(ser.value(), ser.argString());
                }
                if (null == i && ser.argClass().length > 0) {
                    i = MethodChooser.newIntance(ser.value(), ser.argClass());
                }
                if (null == i && ser.argMap().length > 0) {
                    Map<String, Class> map = new HashMap<String, Class>();
                    for (NStringClassPair p : ser.argMap()) {
                        map.put(p.key(), p.value());
                    }
                    i = MethodChooser.newIntance(ser.value(), map);
                }
                if (null == i) {
                    i = MethodChooser.newIntance(ser.value());
                }
                return i;
            } catch (Throwable ex) {
                Logger.getLogger(AnnotationObjSerialize.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return null;
    }

    @Override
    public <T> T toObj(cn.gs.serializable.serialize.ISerialize ctrl, IEntity from, Class<T> clazz) {
        if (clazz == null) {
            return null;
        }
        ISerialize ser = serialize(clazz);
        if (ser != null) {
            return ser.toObj(ctrl, from, clazz);
        }
        return null;
    }

    @Override
    public IEntity fromObj(ISerialize ctrl, Object from) {
        if (from != null) {
            ISerialize ser = serialize(from.getClass());
            if (ser != null) {
                return ser.fromObj(ctrl, from);
            }
        }
        return null;
    }
}
